今天沒什麼時間,決定要來介紹輕鬆又簡單的Lombok,Lombok是一套Java的函式庫,內部包含了許多功能,包括:
以下是一個範例:
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
class Student {
private final int id;
private final String name;
private String status;
private String nickname;
}
這是使用了Lombok,讓我們看看沒使用Lombok的版本 ( 同功能 )
public class Student {
private static final Logger log = LoggerFactory.getLogger(Student.class);
private final int id;
private final String name;
private String status;
private String nickname;
// No-args constructor
public Student() {
this.id = 0;
this.name = null;
this.status = null;
this.nickname = null;
}
// All-args constructor
public Student(int id, String name, String status, String nickname) {
this.id = id;
this.name = name;
this.status = status;
this.nickname = nickname;
}
// Getters
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getStatus() {
return status;
}
public String getNickname() {
return nickname;
}
// Setters
public void setStatus(String status) {
this.status = status;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
// toString
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", status='" + status + '\'' +
", nickname='" + nickname + '\'' +
'}';
}
// equals and hashCode
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return id == student.id &&
Objects.equals(name, student.name) &&
Objects.equals(status, student.status) &&
Objects.equals(nickname, student.nickname);
}
@Override
public int hashCode() {
return Objects.hash(id, name, status, nickname);
}
總之,Lombok利用註解來幫你省去一大筆要慢慢手寫物件建立與讀取方法的時間,我過去也很喜歡使用Lombok,但是他也未必都是好處。以下統整出它的缺點:
以上就是我的分享,那麼我們明天見吧,